package com.haima.sage.bigdata.api.frame.datatype.impl;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.haima.sage.bigdata.api.frame.datatype.DataTypeService;

/**
 * Object类型转换为目标类型Date
 */
public class DateDataTypeService extends DataTypeService<Date> {
    private static final Logger LOG = LogManager.getLogger(DateDataTypeService.class);
    private String pattern;
    private SimpleDateFormat sdf1;
    private SimpleDateFormat sdf2;
    private Pattern regex = Pattern.compile("\\d+");

    public DateDataTypeService(String pattern) {
        this.pattern = pattern;
        try {
            sdf1 = new SimpleDateFormat(pattern, Locale.ENGLISH);
            sdf2 = new SimpleDateFormat(pattern, Locale.CHINESE);
        } catch (Exception e) {
            LOG.error("not support date pattern:{}", pattern, e);
        }
    }

    @Override
    public Date trans(Object value) throws Exception {
        if (null == value) {
            return null;
        }
        if (value instanceof Timestamp) {
            return new Date(((Timestamp) value).getTime());
        } else if (value instanceof Date) {
            return (Date) value;
        } else if (value instanceof Double) { // json 反序列化后
            return new Date(((Double) value).longValue());
        } else if (value instanceof Long) { // Java最常用的时间标签
            return new Date((Long) value);
        } else if (value instanceof Integer) { // UNIX最常用的时间标签
            return new Date(((Integer) value) * 1000);
        } // 格式 解析
        String tmp = value.toString().trim();
        if (regex.matcher(tmp).matches()) {
            long time = Long.parseLong(tmp);
            if (tmp.length() == 13) {
                return new Date(time);
            } else if (tmp.length() == 10) {
                return new Date(time * 1000);
            }
        }
        try {
            return sdf1.parse(tmp);
        } catch (ParseException e) {
            return sdf2.parse(tmp);
        }
    }


    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }
}
